package yk.flutter.platelpr;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Environment;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;

import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.ActivityResultListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 车牌识别插件主类
 * 负责Flutter与Android原生代码的通信桥梁
 */
public class PlateLprPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, ActivityResultListener {
    
    private static final String CHANNEL = "yk.flutter.platelpr";
    private static final int REQUEST_CODE_PLATE_LPR = 1001;
    
    private MethodChannel channel;
    private Context context;
    private Activity activity;
    private Result pendingResult;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), CHANNEL);
        channel.setMethodCallHandler(this);
        context = flutterPluginBinding.getApplicationContext();
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        switch (call.method) {
            case "startPlateLpr":
                startPlateLpr(call, result);
                break;
            case "getPlatformVersion":
                result.success("Android " + android.os.Build.VERSION.RELEASE);
                break;
            case "addWatermark":
                addWatermark(call, result);
                break;
            default:
                result.notImplemented();
                break;
        }
    }

    /**
     * 启动车牌识别界面
     */
    private void startPlateLpr(MethodCall call, Result result) {
        if (activity == null) {
            result.error("NO_ACTIVITY", "Activity未初始化", null);
            return;
        }

        // 保存结果回调
        pendingResult = result;

        // 获取参数
        Map<String, Object> arguments = call.arguments();
        int recogButtonType = 0; // 默认为 hidden
        String title = "车牌识别";
        
        if (arguments != null) {
            if (arguments.containsKey("recogButtonType")) {
                recogButtonType = (Integer) arguments.get("recogButtonType");
            }
            if (arguments.containsKey("title")) {
                title = (String) arguments.get("title");
            }
        }

        // 启动车牌识别Activity
        Intent intent = new Intent(activity, PlateLprActivity.class);
        intent.putExtra("recogButtonType", recogButtonType);
        intent.putExtra("title", title);
        activity.startActivityForResult(intent, REQUEST_CODE_PLATE_LPR);
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PLATE_LPR && pendingResult != null) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 识别成功，返回结果
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("success", true);
                resultMap.put("plateNumber", data.getStringExtra("plateNumber"));
                resultMap.put("confidence", data.getFloatExtra("confidence", 0.0f));
                resultMap.put("imagePath", data.getStringExtra("imagePath"));
                // isNoPlate is derived from plateNumber in Dart, no need to send it.
                
                pendingResult.success(resultMap);
            } else if (resultCode == Activity.RESULT_CANCELED) {
                // 用户取消
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("success", false);
                resultMap.put("error", "用户取消识别");
                
                pendingResult.success(resultMap);
            } else {
                // 识别失败
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("success", false);
                resultMap.put("error", data != null ? data.getStringExtra("error") : "识别失败");
                
                pendingResult.success(resultMap);
            }
            
            pendingResult = null;
            return true;
        }
        return false;
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
        binding.addActivityResultListener(this);
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {
        activity = null;
    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
        binding.addActivityResultListener(this);
    }

    /**
     * 为图片添加水印
     */
    private void addWatermark(MethodCall call, Result result) {
        try {
            String imagePath = call.argument("imagePath");
            // Android颜色值是带符号的32位整数，而Dart颜色值是无符号的，需要用long接收
            long backgroundColorValue = call.argument("backgroundColor");
            long textColorValue = call.argument("textColor");
            String text = call.argument("text");
            double textSize = call.argument("textSize");

            if (imagePath == null || text == null) {
                result.error("INVALID_ARGUMENT", "图片路径或水印文字不能为空", null);
                return;
            }

            // 1. 加载图片
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inMutable = true;
            Bitmap sourceBitmap = BitmapFactory.decodeFile(imagePath, options);
            if (sourceBitmap == null) {
                result.error("FILE_NOT_FOUND", "无法加载图片: " + imagePath, null);
                return;
            }

            Bitmap mutableBitmap = sourceBitmap.copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(mutableBitmap);

            // 2. 配置画笔
            TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
            textPaint.setColor((int) textColorValue);
            textPaint.setTextSize((float) textSize);

            Paint backgroundPaint = new Paint();
            backgroundPaint.setColor((int) backgroundColorValue);

            // 3. 配置StaticLayout用于文本换行
            int padding = (int) (textSize / 2); // 内边距
            int imageWidth = mutableBitmap.getWidth();
            // 文本区域宽度为图片宽度减去两边内边距
            int textWidth = imageWidth - (2 * padding);

            StaticLayout staticLayout = StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, textWidth)
                    .setAlignment(Layout.Alignment.ALIGN_NORMAL)
                    .setLineSpacing(0, 1.0f)
                    .setIncludePad(true)
                    .build();

            // 4. 计算绘制位置
            int textHeight = staticLayout.getHeight();
            int backgroundHeight = textHeight + (2 * padding);
            
            // 将水印放在图片顶部
            float backgroundY = 0;
            float textY = padding;

            // 5. 绘制背景和文字
            canvas.drawRect(0, backgroundY, imageWidth, backgroundHeight, backgroundPaint);
            canvas.save();
            canvas.translate(padding, textY); // 移动画布到绘制文本的起始位置
            staticLayout.draw(canvas);
            canvas.restore();

            // 6. 保存带水印的图片，直接覆盖原文件
            File originalFile = new File(imagePath);
            FileOutputStream outputStream = new FileOutputStream(originalFile);
            mutableBitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream);
            outputStream.flush();
            outputStream.close();

            // 7. 释放资源并返回原图片路径
            sourceBitmap.recycle();
            mutableBitmap.recycle();
            result.success(imagePath);

        } catch (Exception e) {
            e.printStackTrace();
            result.error("WATERMARK_ERROR", "添加水印时发生错误: " + e.getMessage(), null);
        }
    }

    @Override
    public void onDetachedFromActivity() {
        activity = null;
    }
}
